package com.yuncheng.spcyApi.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.busService.BusService;
import com.yuncheng.spcyApi.busService.InitWjjlService;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyCommonConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.wjml.WjmlConstant;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import com.yuncheng.spcyApi.spcyService.SpcyBlgcclService;
import com.yuncheng.spcyApi.utils.GetCurrentUserUtils;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import com.yuncheng.spcyApi.utils.LocalFileUploadUtils;
import com.yuncheng.spcyApi.utils.StringPatternUtils;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.common.base.controller.BaseController;
import com.yuncheng.spcyApi.entity.SpcySqsxWjjl;
import com.yuncheng.spcyApi.service.ISpcySqsxWjjlService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import utils.DateConversionUtils;
import utils.LogUtils;
import utils.ObjectToMapUtils;

/**
 * @Description: 审评查验-文件记录
 * @Author: csx
 * @Date: 2023-03-03
 * @Version: V1.0
 */
@Api(tags = "审评查验-文件记录接口")
@RestController
@RequestMapping("/api/spzx-spcy/spcySqsxWjjl")
public class SpcySqsxWjjlController extends BaseController<SpcySqsxWjjl, ISpcySqsxWjjlService> {

    private static final Logger log = LoggerFactory.getLogger(SpcySqsxWjjlController.class);

    @Resource
    private ISpcySqsxWjjlService spcySqsxWjjlService;

    @Resource
    private ISpcyLogService spcyLogService;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    private BusService busService;

    @Resource
    @Lazy
    private InitWjjlService initWjjlService;

    @Resource
    private SpcyBlgcclService spcyBlgcclService;

    @Log(title = "获取文件后缀-通过文件id")
    @ApiOperation(value = "获取文件后缀-通过文件id")
    @ApiImplicitParam(name = "id",value = "文件id",required = true)
    @GetMapping(value = "getFileType")
    public HttpResult<?> getFileType(@RequestParam(value = "id",defaultValue = "")String id){
        if (StringUtils.isBlank(id)){
            return HttpResult.error("文件id不能为空");
        }
        String fileType = "";
        SpcySqsxWjjl wjjl = spcySqsxWjjlService.getById(id);
        if (wjjl != null && StringUtils.isNotBlank(wjjl.getFwjlx())){
            fileType = wjjl.getFwjlx();
        }
        HttpResult<Object> result = new HttpResult<>(true);
        result.setMessage("获取成功");
        result.setResult(fileType);
        return result;
    }

    @Log(title = "修改文件名称")
    @ApiOperation(value = "修改文件名称")
    @PostMapping(value = "modifyWjMc")
    public HttpResult modifyWjMc(@RequestBody SpcySqsxWjjl paramVo){
        if (StringUtils.isBlank(paramVo.getId())){
            return HttpResult.error("参数为空！");
        }
        if (StringUtils.isBlank(paramVo.getFwjxsmc())){
            return HttpResult.error("文件名称为空！");
        }

        String validFileName = StringPatternUtils.isValidFileName(paramVo.getFwjxsmc());
        if (StringUtils.isNotBlank(validFileName)){
            return HttpResult.error("文件名不能存在特殊字符："+validFileName);
        }

        /*if (paramVo.getFwjxsmc().contains(".")){
            return HttpResult.error("文件名称不能带【.】！");
        }

        if (paramVo.getFwjxsmc().contains("/")){
            return HttpResult.error("文件名称不能带【/】！");
        }*/

        LambdaUpdateWrapper<SpcySqsxWjjl> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SpcySqsxWjjl::getId, paramVo.getId());

        SpcySqsxWjjl updateBean = new SpcySqsxWjjl();
        updateBean.setFwjxsmc(paramVo.getFwjxsmc());
        spcySqsxWjjlService.update(updateBean, updateWrapper);

        return HttpResult.ok("保存成功");
    }

    /**
     * 获取申请事项相关-文件记录
     */
    @Log(title = "获取申请事项相关-文件记录(默认参选企业申报材料)")
    @ApiOperation(value = "获取申请事项相关-文件记录(默认参选企业申报材料)")
    @ApiImplicitParam(name = "sqsxid",value = "申请事项id",required = true)
    @GetMapping(value = "querySqsxWjjlList")
    public HttpResult<?> querySqsxWjjlList(@RequestParam(value = "sqsxid",defaultValue = "")String sqsxId,
                                           SpcySqsxWjjl wjjl){
        if (StringUtils.isBlank(sqsxId)){
            return HttpResult.error("申请事项id为空");
        }
        if (StringUtils.isBlank(wjjl.getFwjlx1())){
            wjjl.setFwjlx1(WjmlConstant.qysbcl);
        }
        Map map = new HashMap();
        LambdaQueryWrapper<SpcySqsxWjjl> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpcySqsxWjjl::getFpid, sqsxId);
        queryWrapper.eq(StringUtils.isNotBlank(wjjl.getFywflcode()),SpcySqsxWjjl::getFywflcode,wjjl.getFywflcode());
        queryWrapper.like(StringUtils.isNotBlank(wjjl.getFwjxsmc()),SpcySqsxWjjl::getFwjxsmc,wjjl.getFwjxsmc());
        queryWrapper.like(StringUtils.isNotBlank(wjjl.getFwjlx1()),SpcySqsxWjjl::getFwjlx1,wjjl.getFwjlx1());
        queryWrapper.like(StringUtils.isNotBlank(wjjl.getFwjlx2()),SpcySqsxWjjl::getFwjlx2,wjjl.getFwjlx2());
        queryWrapper.like(StringUtils.isNotBlank(wjjl.getFwjlx3()),SpcySqsxWjjl::getFwjlx3,wjjl.getFwjlx3());
        queryWrapper.like(StringUtils.isNotBlank(wjjl.getFwjlx4()),SpcySqsxWjjl::getFwjlx4,wjjl.getFwjlx4());
        queryWrapper.like(StringUtils.isNotBlank(wjjl.getFwjlx5()),SpcySqsxWjjl::getFwjlx5,wjjl.getFwjlx5());
        List<SpcySqsxWjjl> wjjlList = spcySqsxWjjlService.list(queryWrapper);

        map.put("wjjlList",wjjlList);
        return HttpResult.ok(map);
    }

    @Log(title = "申请事项文件记录-删除")
    @ApiOperation(value = "申请事项文件记录-删除")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id",value = "文件记录id",dataType = "String",required = true),
    })
    @DeleteMapping(value = "/deleteFileById")
    public HttpResult<?> deleteFileById(@RequestParam(value = "id",defaultValue = "")String fileId){
        if (StringUtils.isEmpty(fileId)){
            return HttpResult.error("文件记录id不能为空！");
        }

        SpcySqsxWjjl wjjl = spcySqsxWjjlService.getById(fileId);
        if (wjjl == null){
            return HttpResult.error("文件记录不存在！");
        }

        if (StringUtils.isNotBlank(wjjl.getFwjlx1()) && wjjl.getFwjlx1().equals(WjmlConstant.xcjcbg)) {
            if (StringUtils.isNotBlank(wjjl.getFwjnr()) && wjjl.getFwjnr().contains("上一次报告")) {
                return HttpResult.error("操作失败，上一次报告无法删除！");
            }
        }

        /** 企业端删除 */
        if (GetCurrentUserUtils.getCurrentUserOrgId().equals(SpcyConstant.QY_ORG_ID)) {
            if (StringUtils.isNotBlank(wjjl.getFwjlx7()) && !wjjl.getFwjlx7().equals(SpcyConstant.QY_SQSX_WJJL_UPLOAD_FLAG)) {
                return HttpResult.error("操作失败，该文件(中心上传材料)无权限删除！");
            }
        }else {
            if (StringUtils.isNotBlank(wjjl.getFwjlx7()) && wjjl.getFwjlx7().equals(SpcyConstant.QY_SQSX_WJJL_UPLOAD_FLAG)) {
                return HttpResult.error("操作失败，该文件(企业上传材料)无权限删除！");
            }
        }

        /** 合并事项文件-只删除记录 */
        if (StringUtils.isNotBlank(wjjl.getFwjlx6()) && wjjl.getFwjlx6().equals(SpcyCommonConstant.QY_WJCL_FBZ_HBSX)){
            spcySqsxWjjlService.removeById(fileId);

            String czContent = "删除申请事项文件: ";
            czContent += LogUtils.MapToStringMethod(ObjectToMapUtils.objectToMap(wjjl));
            spcyLogService.addLogs(LogConstant.LOGS_SQSX_WJJL,czContent, wjjl.getFpid(), "申请事项文件记录-删除",SpcyConstant.LOGS_SYS_TYPE_SC);

            return HttpResult.ok("删除成功");
        }

        spcySqsxWjjlService.removeById(fileId);

        if (StringUtils.isNotBlank(wjjl.getFcflj())) {
            localFileUploadUtils.deleteLocalFileUrl(wjjl.getFcflj());
        }

        if (StringUtils.isNotBlank(wjjl.getFjdcflj())){
            localFileUploadUtils.deleteLocalFileUrl(wjjl.getFjdcflj());
        }

        String czContent = "删除申请事项文件: ";
        czContent += LogUtils.MapToStringMethod(ObjectToMapUtils.objectToMap(wjjl));
        spcyLogService.addLogs(LogConstant.LOGS_SQSX_WJJL,czContent, wjjl.getFpid(), "申请事项文件记录-删除",SpcyConstant.LOGS_SYS_TYPE_SC);

        return HttpResult.ok("删除成功");
    }

    @Log(title = "多类型文件上传")
    @ApiOperation(value = "多类型文件上传")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "file",value = "文件不能为空",required = true),
            @ApiImplicitParam(name = "sqsxid",value = "申请事项id",required = true),
            @ApiImplicitParam(name = "type",value = "文件模板类型",required = true),
    })
    @PostMapping(value = "/uploadMoreTypeFile")
    public HttpResult<?> uploadMoreTypeFile(@RequestPart("file") MultipartFile[] uploadFile,
                                            @RequestParam(value = "sqsxid",defaultValue = "") String sqsxid,
                                            @RequestParam(value = "type",defaultValue = "") String type,
                                            SpcySqsxWjjl spcySqsxWjjl){

        if (uploadFile == null || uploadFile.length == 0) {
            return HttpResult.error("上传失败,请先选择文件");
        }

        if (StringUtils.isEmpty(sqsxid)){
            return HttpResult.error("事项参数为空！");
        }

        if (StringUtils.isBlank(type)) {
            if (StringUtils.isNotBlank(spcySqsxWjjl.getFwjlx1())) {
                type = spcySqsxWjjl.getFwjlx1();
            }else {
                return HttpResult.error("请选择要上传文件类型！");
            }
        }

        initWjjlService.uploadSqsxFile(uploadFile, sqsxid, type, false);

        return HttpResult.ok("上传成功");
    }

    @Log(title = "上传pdf文件/替换旧的文件")
    @ApiOperation(value = "上传pdf文件/替换旧的文件")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "file",value = "文件不能为空",required = true),
            @ApiImplicitParam(name = "id",value = "文件id",required = true)
    })
    @PostMapping(value = "uploadPdfFileById")
    public HttpResult<?> uploadPdfFileById(@RequestPart("file") MultipartFile file,
                                           @RequestParam(value = "id",defaultValue = "") String id){

        if (StringUtils.isEmpty(id)){
            throw new BusinessException("文件参数不能为空！");
        }

        SpcySqsxWjjl wjjl = spcySqsxWjjlService.getById(id);
        if (wjjl == null){
            throw new BusinessException("当前文件记录不存在，请刷新重试！");
        }

        String sqsxid = wjjl.getFpid();

        String originalFilename = file.getOriginalFilename();

        // 文件类型
        String wjlx = originalFilename.substring(originalFilename.lastIndexOf("."));

        if (!wjlx.equals(".pdf")){
            throw new BusinessException("请上传pdf文件！");
        }

        String wjccmc = GetUuIdUtils.NotReplaceUuId() + wjlx;

        String wjml = DateConversionUtils.DateToMonthTwo(new Date());
        localFileUploadUtils.uploadSqsxFile(file, wjml, wjccmc); // 上传文件

        // 存放不是pdf的文件,将文档放入旧的路径
        if (StringUtils.isNotBlank(wjjl.getFwjlx()) && !wjjl.getFwjlx().equals(".pdf")){

            if (StringUtils.isNotBlank(wjjl.getFjdcflj())) {
                localFileUploadUtils.deleteLocalFileUrl(wjjl.getFjdcflj()); // 删除旧文件
            }

            wjjl.setFjdcflj(wjjl.getFcflj());
        }

        // 为pdf删除
        if (StringUtils.isNotBlank(wjjl.getFwjlx()) && wjjl.getFwjlx().equals(".pdf") && StringUtils.isNotBlank(wjjl.getFcflj())){
            localFileUploadUtils.deleteLocalFileUrl(wjjl.getFcflj()); // 删除旧文件
        }

        wjjl.setFwjlx(wjlx);
        wjjl.setFwjccmc(wjccmc);
        String cflj = "/" + wjml + "/" + wjccmc;
        wjjl.setFcflj(cflj);
        wjjl.setFgzzt(SpcyConstant.WJJL_ZT_GZ_NO);
        wjjl.setFdxzt(SpcyConstant.WJJL_ZT_DX_NO);
        wjjl.setFyxzt(SpcyConstant.WJJL_ZT_YX_NO);
        spcySqsxWjjlService.updateById(wjjl);

        String hjmc = busService.getNowNodeName(sqsxid); // 当前环节名称

        String czContent = "上传文件/替换旧的文件: ";
        Map<String, Object> wjjlMap = ObjectToMapUtils.objectToMap(wjjl);
        czContent += LogUtils.MapToStringMethod(wjjlMap);
        spcyLogService.addLogs(hjmc,czContent,sqsxid,LogConstant.LOGS_SQSX_WJJL,SpcyConstant.LOGS_SYS_TYPE_BC);

        return HttpResult.ok("上传成功");
    }

    @Log(title = "申请事项文件下载")
    @ApiOperation(value = "申请事项文件下载")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id",value = "文件记录id",required = true)
    })
    @GetMapping(value = "/getLocalFileById")
    public void getLocalFileById(@RequestParam(value = "id",defaultValue = "") String fileId,
                                 @RequestParam(value = "symc",defaultValue = "") String symc,
                                 HttpServletResponse response) throws IOException {
        if (StringUtils.isEmpty(fileId)){
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println("文件参数为空！");
            writer.close(); // 不要忘记关闭PrintWriter

            return;
        }

        if (fileId.contains("@")){
            spcyBlgcclService.downWjmlBySchyQy(fileId, response);

        }else {

            SpcySqsxWjjl wjjl = spcySqsxWjjlService.getById(fileId);
            if (wjjl == null) {
                response.setContentType("text/html");
                response.setCharacterEncoding("UTF-8");
                PrintWriter writer = response.getWriter();
                writer.println("文件记录不存在！");
                writer.close(); // 不要忘记关闭PrintWriter

                return;
            }

            // 是否为水印-下载文件
            if (StringUtils.isBlank(symc)) {
                localFileUploadUtils.ejzLocalFileURl(wjjl.getFcflj(), response);

            } else {

                symc = GetCurrentUserUtils.getCurrentUserName() + DateConversionUtils.DateToString(new Date());
                localFileUploadUtils.ejzSqsxFileURLSy(wjjl.getFcflj(), wjjl.getFwjlx(), symc, response);
            }

        }
    }

    @ApiOperation(value = "申请事项文件预览")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id",value = "文件记录id",required = true),
            @ApiImplicitParam(name = "symc",value = "水印名称(有值代表添加水印)")
    })
    @GetMapping(value = "/getCrossLocalFile")
    public void getCrossLocalFile(@RequestParam(value = "id",defaultValue = "") String fileId,
                                  @RequestParam(value = "symc",defaultValue = "") String symc,
                                  HttpServletResponse response) throws IOException {
        if (StringUtils.isEmpty(fileId)){
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println("文件参数为空！");
            writer.close(); // 不要忘记关闭PrintWriter

            return;
        }

        SpcySqsxWjjl wjjl = spcySqsxWjjlService.getById(fileId);
        if (wjjl == null){
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println("文件记录不存在！");
            writer.close(); // 不要忘记关闭PrintWriter

            return;
        }

        // 是否为水印-下载文件
        if (StringUtils.isBlank(symc)) {
            localFileUploadUtils.ejzLocalFileURl(wjjl.getFcflj(), response);
        }else {
            localFileUploadUtils.ejzSqsxFileURLSy(wjjl.getFcflj(), wjjl.getFwjlx(), null, response);
        }
    }

}
